package com.teemor.common.bean.utils.tools;

import com.alibaba.fastjson.JSON;
import com.teemor.common.bean.model.EmailModel;
import com.teemor.common.bean.utils.redis.RedisUtils;
import com.teemor.common.bean.utils.kafka.BaseKafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description:
 * @author zhoulk
 * @date: 2020/3/3
 */
public class EmailTool {

    private static final Logger LOGGER = LoggerFactory.getLogger(EmailTool.class);

    private static BaseKafkaProducer producer;
    private static String KEY_PRE = "EMAIL-";

    /****
     * 默认配置：每30分钟同一用户只能发送5次同类型邮件
     * ****/
    private static Integer DEFAULT_SECONDS = 60 * 30;
    private static Integer DEFAULT_COUNT = 5;

    private static String KAFKA_TOPIC = "EMAIL_TOPIC";

    public static void sendEmail(EmailModel emailModel) {
        ProducerRecord<Integer, String> producerRecord = new ProducerRecord<>(KAFKA_TOPIC, JSON.toJSONString(emailModel));
        BaseKafkaProducer.sendMessage(producerRecord);
    }

    /**
     *
     * @param emailModel 邮件信息
     * @param seconds   限流时间段
     * @param count 限流次数
     * @return
     */
    public static int sendEmail(EmailModel emailModel, Integer seconds, Integer count) {
        String address = emailModel.getAddress();
        String key = KEY_PRE + address;
        int n = RedisUtils.simpleLimit(key, seconds, count);
        if (n > 0) {
            sendEmail(emailModel);
        }
        return n;
    }


    public static int sendEmailCode(String address, String code) {
        EmailModel emailModel = new EmailModel();
        emailModel.setAddress(address);
        emailModel.setMsg("验证码为：" + code);
        emailModel.setTimestamp(System.currentTimeMillis());
        emailModel.setType(1);
        emailModel.setTitle("验证码");
        return sendEmail(emailModel, DEFAULT_SECONDS, DEFAULT_COUNT);
    }

    public static void sendEmailMessage(String address, String msg) {
        EmailModel emailModel = new EmailModel();
        emailModel.setAddress(address);
        emailModel.setMsg(msg);
        emailModel.setTimestamp(System.currentTimeMillis());
        emailModel.setType(2);
        emailModel.setTitle("通知");
        sendEmail(emailModel);
    }


}
